<template>
  <div class="layout-good-price">
    <el-form ref="form" :model="brandProduct" label-width="100px" label-position="left" size="small">
      <el-form-item label="品牌" >
        <el-input v-model="brandProduct.brandName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="产品" >
        <el-input v-model="brandProduct.productName" :disabled="true"></el-input>
      </el-form-item>
            <el-form-item label="厂商" >
        <el-input v-model="brandProduct.partnerName" :disabled="true"></el-input>
      </el-form-item>
    </el-form>
    <div class="scale-bar">
      <el-table :data="priceRuleList" class="price-scale-table" border size="small">
        <el-table-column label="价格">
          <template slot-scope="scope">{{ scope.row.indentityName }}</template>
        </el-table-column>
        <el-table-column label="联动方式">
          <template slot-scope="scope">
            <el-select v-model="scope.row.relateWay" placeholder="联动方式" size="small"  @change="changeway(scope.row)">
              <el-option
                v-for="item in priceModeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="联动对象">
          <template slot-scope="scope">
            <div >
            <el-select v-if="scope.row.relateWay==2" v-model="scope.row.relateObj" placeholder="联动对象" size="small">
              <el-option
                v-for="item in priceNameList"
                :key="item.itemCode"
                :label="item.itemName"
                :value="item.itemCode"
              ></el-option>
            </el-select>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="联动系数/固定值">
          <template slot-scope="scope">
            <el-input-number
              v-if="scope.row.relateWay==2"
              v-model="scope.row.rate"
              :step="0.01"
              :controls="false"
              :change="onchange(scope.row)"
              size="small"
              step-strictly
            ></el-input-number>
             <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-table :data="list" v-loading="listLoading" class="good-price-table" size="small">
    <el-table-column label="规格" align="center">
    <el-table-column v-for="item in productSpes" :key="item.spec" :label="item.specName" width="120">
            <template slot-scope="scope">{{getSpecValue(scope.row.goodsSpecList,item.specCode)}}</template>
    </el-table-column>
        {{this.priceRuleList}}
      </el-table-column>
      <el-table-column label="价格" align="center">
       <el-table-column v-for="item in priceRuleList" :key="item.indentity" :label="item.indentityName" width="120">
            <!-- <template slot-scope="scope">{{getSpecValue(scope.row.goodsSpec,item.specCode)}}</template> -->
            <template slot-scope="scope">
            <el-input-number
              v-if="isEdit(item.indentity)"
              v-model="scope.row.priceMap[item.indentity].price"
              :step="0.01"
              :controls="false"
              size="small"
              step-strictly
            ></el-input-number>
            <span v-else>{{ scope.row.priceMap[item.indentity].price }}</span>
          </template>
          </el-table-column>
      </el-table-column>
    </el-table>
       <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="Save()">保存</el-button>
      <el-button @click="handleClear()">取消</el-button>
    </div>
  </div>

</template>

<script>
import {getBrandProductDetail,saveBrandProductPriceRule} from '@/api/brandProduct';
import {getBrandGoodsByProductAndBrand} from '@/api/brand';
import {getLookup} from '@/api/common';
import {querySpecByProductCode} from '@/api/goods'
import {queryAllPriceByBrandProduct,queryBrandProductPriceRule} from '@/api/price'
export default {
  name: "Price",
  components: {},
  data() {
    return {
      priceRuleList: [],
      list: [],
      lookup:[],
      listLoading: false,
      priceModeList: [],
      priceNameList: [],
      priceFixList: [],
      productSpes:[],
      brandProduct:{
        brandName:'',
        brandCode:'',
        productCode:'',
        productName:'',
        partnerCode:'',
        partnerName:'',
        rules:[]
      }
    };
  },
  computed: {},
  created() {
      getBrandProductDetail(this.$route.query).then(response=>{
      this.brandProduct=response.data;
      debugger
       querySpecByProductCode({productCode:this.brandProduct.productCode}).then(res => {
        if (res.code === 200) {
          this.productSpes = res.data;
        }
      })

       getLookup("Indentity").then(response=>{
         debugger
      this.lookup=response.data;
      queryBrandProductPriceRule({productCode:this.brandProduct.productCode,brandCode:this.brandProduct.brandCode}).then(result=>{
        var res = result.data;
         
        this.lookup.forEach(item=>{
        var priceRule = {};
        priceRule.productCode=this.brandProduct.productCode;
        priceRule.productName=this.brandProduct.productName;
        priceRule.brandCode=this.brandProduct.brandCode;
        priceRule.indentity=item.itemCode;
        priceRule.indentityName=item.itemName;
        if(res.length>0){
        var rule = res.filter(pr => {
        if (pr.indentity == item.itemCode) {
          return pr;
        }});
        debugger;
        if(rule.length>0){
        priceRule.rate = rule[0].rate
        priceRule.fixPrice = rule[0].fixPrice
        priceRule.relateObj = rule[0].relateObj
        priceRule.relateWay = rule[0].relateWay
        if( rule[0].relateWay==1){
           this.priceNameList.push(item);
        }
        }
        }
        this.priceRuleList.push(priceRule);
        });



        })

      }),
      //  getBrandGoodsByProductAndBrand({productCode:this.brandProduct.productCode,brandCode:this.brandProduct.brandCode}).then(res => {
      // // this.list=res.data
      // });
         queryAllPriceByBrandProduct({productCode:this.brandProduct.productCode,brandCode:this.brandProduct.brandCode}).then(res => {
        this.list=res.data
        this.list.forEach(item=>{
          let obj = {};
          item.priceList.forEach(price=>{
            let key = price.indentity;
            obj[key] = price;
          })
          item.priceMap=obj
        })
        console.log(this.list)
       })
      })
,
    
     
     
     
   
    this.priceModeList = [
      {
        label: "厂商上传",
        value: "1"
      },
      {
        label: "比率",
        value: "2"
      },
      {
        label: "固定值",
        value: "3"
      }
    ]
    
  },
  methods: {
    changeway(val){
    console.log(val)
    if(val.relateWay==1){
      var lookupItems =this.lookup.filter(item => {
        if (item.itemCode == val.indentity) {
          return item;
        }});
      var item1 =this.priceNameList.filter(item => {
        if (item.itemCode == lookupItems[0].itemCode) {
          return item;
        }});
        if(item1.length==0){
        this.priceNameList.push(lookupItems[0]);
        }
         
    }else{
      ;if(this.priceNameList.length==0){
        this.$message({
              type: 'faile',
              message: '请先选择厂商上传对象'
            });
            return
    }
       var item1 =this.priceNameList.filter(item => {
        if (item.itemCode ==  val.indentity) {
          return item;
        }});
         if(item1.length>0){
      this.priceNameList.forEach(function (item,index,array) {
            if(item.itemCode===item1[0].itemCode){
              array.splice(index,1);
            }

       })
        }
    }

 if(val.relateWay==3){
      var lookupItems =this.lookup.filter(item => {

        if (item.itemCode == val.indentity) {
          return item;
        }});
      var item1 =this.priceFixList.filter(item => {
        if (item.itemCode == lookupItems[0].itemCode) {
          return item;
        }});
        if(item1.length==0){
        this.priceFixList.push(lookupItems[0]);
        }
         
    }else{
       var item1 =this.priceFixList.filter(item => {
        if (item.itemCode ==  val.indentity) {
          return item;
        }});
         if(item1.length>0){
      this.priceFixList.forEach(function (item,index,array) {
            if(item.itemCode===item1[0].itemCode){
              array.splice(index,1);
            }

       })
        }
    }
    },
    isEdit(itemCode){
         var item1 =this.priceFixList.filter(item => {
        if (item.itemCode ==itemCode) {
          return item;
        }});
        if(item1.length>0){
          return true;
        }
        return false;
    },
    handleEdit(row) {
      row.isEdit = true;
    },
    onchange(row) {
       if(row.relateWay=='2'&&row.rate!=undefined){
      if(row.relateObj==undefined){
          this.$message({
              type: 'faile',
              message: '必须选择关联对象!'
            });
            return
      }
     
     this.list.forEach(item=>{
  var price = item.priceMap[row.relateObj].price
     item.priceMap[row.indentity].price = this.accMul(price,row.rate,2)
        })
   
    }},
    handleSave(row) {
      row.isEdit = false;
    },
    Save() {
      this.priceRuleList.forEach(item=>{
      if(item.relateWay==3){
           let obj = {};
          this.list.forEach(item1=>{          
           let key = item1.goodsCode;
           obj[key] = item1.priceMap[item.indentity].price
        })
          item.fixPrice = JSON.stringify(obj)

      }
                    item.productCode=this.brandProduct.productCode;
        item.productName=this.brandProduct.productName;
        item.brandCode=this.brandProduct.brandCode;
      })
      saveBrandProductPriceRule( this.priceRuleList);
    },
    accMul(arg1,arg2,fix) { 
    if(!parseInt(fix)==fix)
    {
        return;
    }
     var m=0,s1=arg1.toString(),s2=arg2.toString(); 
     try{m+=s1.split(".")[1].length}catch(e){} 
     try{m+=s2.split(".")[1].length}catch(e){}
     if(m>fix){
        return (Math.round(Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m-fix))/Math.pow(10,fix));
     }else if(m<=fix){
         return (Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)).toFixed(fix);
     }else{
        return (arg1*arg2).toFixed(fix);
     }
} ,
    getSpecValue(val, specCode) {
      if (val == null) {
        return;
      }
      var array = val.filter(item => {
        if (item.specCode === specCode) {
          return item;
        }
      });
      if (array == undefined || array.length <= 0) {
        return;
      }
      return array[0].specValue;
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.layout-good-price {
  max-width: 1200px;
  margin: 0 auto;
  padding-top: 20px;
  .good-price-table {
    .el-input-number--small {
      width: 100%;
    }
  }
  .scale-bar {
    margin-bottom: 10px;
    .tips {
      line-height: 30px;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 10px;
    }
  }
  .price-scale-table /deep/ {
    th.el-table__cell {
      background-color: #f5f7fa;
    }
    .el-input-number {
      width: 100%;
    }
  }
}
</style>